package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.data.RobotMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Robot;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 登出接口3.0（兼容PC）回调
 *
 * <pre>
 * {
 *     "vcMerchantNo": "202309130012311",
 *     "vcRobotWxId": "wxid_eknqssxstya922",
 *     "vcRobotSerialNo": "58300812F01A1C02CCC59A14F121912F",
 *     "vcSerialNo": "20250113171500105597210200038",
 *     "nType": 1005,
 *     "nResult": 1,
 *     "vcResult": "Success",
 *     "nTimeStamp": 1736759700336,
 *     "Data": {
 *         "extend": "",
 *         "nLoginType": 11,
 *         "nOfflineCode": "10009",
 *         "vcOfflineReason": "IP变动频繁",
 *         "vcRelationSerialNo": "",
 *         "nLogType": 0,
 *         "user_serial_no": "NTgzMDA4MTJGMDFBMUMwMkNDQzU5QTE0RjEyMTkxMkY6NA==",
 *         "time_stamp": 1736759700058
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class _1005Handler implements CallbackHandler {

    @Resource
    private RobotMapper robotMapper;

    @Override
    public String name() {
        return "机器人登出回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 1005;
    }

    @Override
    public void handle(Callback callback) {
        Long id = callback.getId();
        String serialNo = callback.getSerialNo();
        String robotId = callback.getRobotId();
        String robotSerialNo = callback.getRobotSerialNo();

        JSONObject data = (JSONObject) callback.getData();
        Robot robot = robotMapper.selectById(robotId);
        if (robot == null) {
            log.error("机器人不存在[id:{}, serialNo:{}, robotId:{}, robotSerialNo:{}]",
                    id, serialNo, robotId, robotSerialNo);
            return;
        }
        robot.setLoginType(data.getInteger("nLoginType"))
                .setLogType(data.getInteger("nLogType"))
                .setOnline(false)
                .setOfflineCode(data.getString("nOfflineCode"))
                .setOfflineReason(data.getString("vcOfflineReason"))
                .setOfflineTime(LocalDateTime.ofInstant(data.getInstant("time_stamp"), ZoneId.systemDefault()))
                .setUpdatedTime(LocalDateTime.now());
        robotMapper.updateById(robot);
    }
}
